<template>
  <div class="release-wrapper">
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content release" v-show="true">
      <e-heading>填写详情</e-heading>
      <el-form :model="form" :rules="rules" label-width="142px" ref="form" v-bind="getFormProps()">
        <!-- 固定块 -->
        <e-heading grade="2">基本信息</e-heading>
        <!-- 当前只有票务 和 普通商品需要选择类目 -->
        <el-form-item label="服务类目："
          prop="serviceCate">
          <span>{{stateConfig.cateName || ''}}</span>
        </el-form-item>
        <!-- 根据各自服务卡的需求添加，不做处理 -->
        <el-form-item label="名称："
          prop="goodsName"
          :rules="[
            { required: !0, message: '名称不能为空'},
          ]">
          <el-col :span="20">
            <el-input class="goodsName" v-model="form.goodsName" :disabled="serviceType.goodsNameEditState" :maxlength="60" number-word />
          </el-col>
        </el-form-item>
        <el-form-item label="卖点："
          prop="sellPoint">
          <el-col :span="20">
            <el-input v-model="form.sellPoint" :maxlength="150" type="textarea" :rows="4" number-word />
          </el-col>
        </el-form-item>
        <!--后台配置块  -->
        <el-row v-show="form.basicProps.length">
          <e-heading grade="2">基本属性</e-heading>
          <el-form-item label="品牌：" prop="brand"
            :rules="[
              { required: !1, message: '请选择品牌'},
            ]">
            <el-col :span="20">
              <el-select placeholder="请选择" v-model="form.brand" class="input-middle">
                <el-option v-for="item in brandList" :key="item.brandCode" :label="item.brandName" :value="item.brandCode" />
              </el-select>
              <el-button type="text" @click="brandAddState = true">添加品牌</el-button>
            </el-col>
          </el-form-item>
          <!-- 自定义项 所有相同 -->
          <form-item
            v-for="(item, index) in form.basicProps"
            formKey="basicProps"
            :key="item.name"
            :index="index"
            :data.sync="item"/>
        </el-row>
        <!-- 销售属性待定 -->
        <el-row v-show="form.saleProps.length">
          <e-heading grade="2">销售信息</e-heading>
          <!-- 销售属性 -->
          <el-form-item label="销售属性："
            :rules="[
              {required: !0, message: '请选择销售属性'}
            ]">
            <el-row
              class="sale-props-item"
              v-for="(item, index) in form.saleProps"
              :key="index">
              <div class="group-title">
                {{item.attrName}}
                <span v-if="item.remarks" class="form-help">( {{item.remarks}} )</span>
              </div>
              <checkbox-groups
                v-model="item.data"
                :min="1"
                :data="item"
                :index="index"
                @change="handleSalePropsChange"/>
            </el-row>
          </el-form-item>
          <!-- 销售规格 -->
          <el-form-item label="销售规格："
            prop="tableData"
            :rules="[
              {required: !0, message: '请输入销售规格'},
              Object.assign({}, validator.rule.saleArray)
            ]">
            <el-col :span="24">
              <div class="tips tips-left" v-if="serviceType.isHasLimitBuy">限购数量为<span class="num">0</span>时，代表不限购</div>
              <div class="tips tips-left">求苗价必须是0~99999之间的数字，且不能高于市场价，此价格为商品实际销售价格</div>
              <sale-spec-table
                :tableData.sync="form.tableData"
                :columData="form.saleProps"
                @change="handleTableDataChange"/>
            </el-col>
          </el-form-item>
        </el-row>
        <e-heading grade="2">详情描述</e-heading>
        <!-- 根据各自服务卡的需求添加，不做处理 -->
        <el-form-item label="上传图片："
          prop="imageList"
          :rules="[
            { required: true, message: '请上传图片'},
          ]">
          <e-img-group-upload v-model="form.imageList" :limit="10" />
          <div class="form-help warn-tips">图片支持jpg、gif、png格式，建议使用尺寸500x500像素以上；大小不超过1M的正方形图片；</div>
        </el-form-item>
        <!-- 赛事详情 -->
        <!-- 根据各自服务卡的需求添加，不做处理 -->
        <el-form-item label="服务详情："
          prop="goodsDesc"
          :rules="[
            { required: !0, message: '请输入服务详情'}
          ]">
          <e-editor v-model="form.goodsDesc" :maxlength="10000" :options="ueditConfig.options" :toolbars="ueditConfig.toolbars"/>
          <div class="form-help warn-tips mt10">文字不超过10,000字，图片支持jpg、gif、png格式，大小不超过1M的正方形图片；</div>   
        </el-form-item>
        <e-heading grade="2" v-if="serviceType.isMatch || form.otherProps.length || form.buyTimes.length">其他信息</e-heading>
        <!-- 自定义项 所有相同 -->
        <form-item
          v-for="(item, index) in form.otherProps"
          formKey="otherProps"
          :key="item.name"
          :index="index"
          :data.sync="item"/>
        <!--培训 培训报名选项 -->
        <train-sign-filed v-if="serviceType.isTrain" v-model="form.trainSignFiled"/>
        <!--培训 上架时间  -->
        <train-shelf-time v-if="serviceType.isTrain" :shelfLevel.sync="shelfLevel" :formData.sync="form"></train-shelf-time>
        <!-- 公共部分 统一 -->
        <div class="button-box">
          <!--loading是必需在绑定的 native-type="submit"修改button type类型-->
          <el-button native-type="button" :loading="draftLoading" @click="handleDraft">保存草稿</el-button>
          <!-- 防止 重复提交修改  只有当 saveLoading loading都为false时，才启用按钮-->
          <el-button type="primary" native-type="submit" :loading="saveLoading">{{subBtnName}}</el-button>
          <el-button type="primary" :disabled="!previewState" @click="handlePreview('pc')">PC预览</el-button>
          <el-button type="primary" :disabled="!previewState" @click="handlePreview('app')">APP预览</el-button>
          <div class="form-help save-help mt10">使用预览功能前，请先保存草稿。</div>
        </div>
      </el-form>
    </div>
    <!-- 公共部分 统一 -->
    <el-dialog
      custom-class="qrcode-dialog"
      :visible="qrCodeState"
      :before-close="() => {qrCodeState = false}">
      <div class="title">为了更好的预览效果，请使用手机扫描</div>
      <e-qr-code class="qr-code-img" v-if="qrCodeText" :height="232" :width="232" :text="qrCodeText"/>
    </el-dialog>
    <brand-form :visible.sync="brandAddState" @change="handleAddBrand"/>
  </div>
</template>

<script>
// 公共组件
import EQrCode from '@e-ui/QrCode' // 二维码 公共
import EEditor from '@e-ui/Editor' // 富文本 公共
import EImgGroupUpload from '@e-ui/ImgGroupUpload' // 上传图片 公共
import FormItem from './components/FormItem' // 自定义项 公共
import SaleSpecTable from './components/SaleSpecTable' // 销售规格 公共
import CheckboxGroups from './components/CheckboxGroups' // 销售属性 公共

// 培训组件
import BrandForm from './components/BrandForm' // 培训品牌自定义 培训
import TrainSignFiled from './components/TrainSignFiled' // 培训报名选项  培训
import TrainShelfTime from './components/TrainShelfTime' // 培训上架时间  培训

import { mapGetters } from 'vuex'
import filters from 'src/filters'
import { cloneObj } from 'utils'
import validator from 'utils/validator'
import serviceApi from 'api/service'
import {form} from 'utils/mixins' // 引入form mixin

import {
  MATCH_REG,
  TRAIN_REG,
  TICKET_REG,
  SHELF_LEVEL, // 上架类型
  EDIT_TYPE_ENUMS,
  FORM_TYPE_ENUMS,
  PROPS_TYPE_ENUMS,
  SHELVE_TIME_FORMAT,
  BASE_TABLE_ROW_DATA,
  MATCH_ABLE_EDIT_SALES, // 赛事可编辑销售属性类目
  MATCH_GROUP_CODE, // 赛事团体
  UEDITOR_CONFIG, // 富文本配置项
  MATCH_CATE_LIST, // 赛事类目展开列表
  TRAIN_CATE_LIST, // 培训类目展开列表
  TRAIN_SALE_ITEM // 培训次课类目
} from './constant'

export default {
  mixins: [form],
  components: {
    EQrCode,
    EEditor,
    FormItem,
    CheckboxGroups,
    SaleSpecTable,
    EImgGroupUpload,
    // 培训
    BrandForm,
    TrainSignFiled,
    TrainShelfTime
  },
  computed: {
    ...mapGetters({
      'serviceType': 'service_release_type', // 类目类型 区分 赛事 培训 票务等
      'formItemProp': 'service_release_formitem'
    }),
    releaseType () {
      let result = 1
      let type = this.$route.params.type
      if (['match', 'train'].indexOf(type) !== -1) { // 活动 虚拟商品 赛事 培训
        result = 1
      } else { // 实体商品  除了赛事培训 都是这个
        result = 2
      }
      return result
    },
    goodsCode () {
      return this.$route.query.goodsCode
    },
    cateCode () {
      return this.$route.query.cateCode
    },
    editorType () {
      return this.$route.query.editType
    },
    subBtnName () {
      return this.editorType === EDIT_TYPE_ENUMS.REPUBLISH ? '重新发布' : '确认提交'
    },
    shelveTime: {
      set (val) {
        this.form.shelveTime = val ? filters.FormatDate(val, SHELVE_TIME_FORMAT) : ''
      },
      get () {
        return this.form.shelveTime
      }
    }
  },
  watch: {
    'formItemProp.properties': 'handleTrainPropChange'
  },
  created () {
    this.$store.commit('SERVICE_RELEASE_EMPTY_STATE') // 清空状态
    this._beforeInitData()
    // window.tyler = this
  },
  data () {
    return {
      SHELF_LEVEL: SHELF_LEVEL,
      saveLoading: !1, // 保存loading
      draftLoading: !1, // 保存草稿loading
      loading: !1, // 必需要返回loading
      validator,
      rules: {},
      _categoryList: [], // 未处理的类目
      categoryList: [], // 类目
      brandList: [], // 品牌列表
      basicPropsObj: {}, // 存储基本属性的信息
      // editorData: {},
      groupItems: [],
      shelfLevel: SHELF_LEVEL.NOW, // 上架时间类型
      shelveTimeRules: [{required: !0}],
      stateConfig: {
        isCateCas: true, // 服务类目是否为级联  默认为级联 赛事培训类目展开后变为文本
        sellPointState: true, // 卖点
        brandState: true, // 品牌
        customBrandState: false // 自定义品牌
      },
      ueditConfig: UEDITOR_CONFIG,
      form: {
        serviceCate: [], // 服务类目
        goodsName: '', // 商品名称
        sellPoint: '', // 卖点
        brand: '',
        basicProps: [], // 基本属性
        matchMode: '', // 比赛方式
        matchOrder: [], // 比赛场序
        saleProps: [], // 销售属性
        otherProps: [], // 其他信息
        tableData: [],
        imageList: [], // 上传图片
        goodsDesc: '',
        goodsMoblieDesc: '', // 手机端描述
        trainSignFiled: {}, // 培训报名
        matchSignFiled: {}, // 赛事报名
        channelList: [ // 报名渠道
          {
            isDefault: true,
            key: this.unique(),
            channelName: '求苗',
            channelsGroup: []
          }
        ],
        buyTimes: [], // 购买起止时间  => 票务
        shelveWay: '', // 上架方式
        trainShelveTimeCheck: '', // 培训上下架时间两个变量可以做只选任意一项，需要个中间变量处理
        shelveTime: filters.FormatDate(new Date(), SHELVE_TIME_FORMAT), // 上架时间  初始值
        offShelveTime: filters.FormatDate(new Date(), SHELVE_TIME_FORMAT) // 下架时间  初始值
      },
      previewState: false, // 预览状态 需要保存草稿后才能预览
      qrCodeState: false,
      qrCodeText: '', // 二维码
      brandAddState: false // 添加品牌弹窗
    }
  },
  methods: {
    _beforeInitData () {
      let serviceState = this._initServiceState(this.cateCode)
      if (serviceState.isMatch || serviceState.isTrain) {
        /**
         * 展开类目的处理方式
         * 赛事 / 培训  均为展开类目
         * 直接触发选择类目事件
         * 隐藏卖点  品牌
         * 找不到curReleaseItem 应为用户乱改url其他问题
         * 现处理方式为不提示 不中断，提供原来的方式让用户新增
         */
        let cateList = MATCH_CATE_LIST.concat(TRAIN_CATE_LIST) // 不区分赛事培训
        let curReleaseItem = cateList.find(item => item.cateCode === this.cateCode)
        if (curReleaseItem) {
          let serviceCate = [this.cateCode]
          this.form.serviceCate = serviceCate
          this.stateConfig.isCateCas = false
          this.stateConfig.cateName = curReleaseItem.title
          if (!this.editorType) {
            this.handleCateChange(serviceCate)
          } else {
            this.getActivityData()
          }
        }
        if (serviceState.isTrain) {
          this.stateConfig.customBrandState = true // 培训开放自定义品牌
        }
        // 只有赛事隐藏卖点和品牌
        if (serviceState.isMatch) {
          this.stateConfig.brandState = false
          this.stateConfig.sellPointState = false
        }
      } else {
        // 未展开类目处理
        this.initCateData()
      }
      // 草稿预览处理
      if (serviceState.editorType === EDIT_TYPE_ENUMS.DRAFTS) {
        setTimeout(_ => {
          this.previewState = true // 显示可以预览
        })
      }
    },
    initCateData () {
      // 初始化服务类目数据
      serviceApi.gategoryList({cateType: this.releaseType}).then(({ data = [], result, msg }) => {
        this._categoryList = data
        this.categoryList = this._recursionArr(data)
        if (this.editorType) { // 编辑
          this.getActivityData()
        }
      })
    },
    getActivityData () {
      if (this.editorType === EDIT_TYPE_ENUMS.REPUBLISH) {
        // 获取重新发布详情
        serviceApi.republishGoods({
          goodsCode: this.goodsCode
        }).then(({data}) => {
          this.initActivityData(data)
        })
      } else {
        // 获取详情
        serviceApi.editGoods({
          cateCode: this.cateCode,
          goodsCode: this.goodsCode
        }).then(({data}) => {
          this.initActivityData(data)
        })
      }
    },
    initActivityData (data) {
      this.editorData = data || {}
      this.editorData.goodsBaseInfo = JSON.parse(this.editorData.goodsBaseInfo)
      this.editorData.goodsExtInfo = JSON.parse(this.editorData.goodsExtInfo)
      // 兼容类目展开 和 不展开情况
      this.form.serviceCate = this.categoryList.length ? this._getCateListByCateCode(data.goodsCateCode) : [data.goodsCateCode] // 服务类目 需要筛选显示
      this.handleCateChange(this.form.serviceCate) // 获取模板
      this.form.bizId = data.bizId // id 用于更新数据
      this.form.goodsCode = data.goodsCode // 用于更新数据
      this.form.goodsName = data.goodsName // 商品名称
      this.form.sellPoint = data.remarks // 卖点
      this.form.brand = data.brandCode // 品牌
      this.form.goodsDesc = data.descPc // 电脑描述
      this.form.attributeMappingList = data.attributeMappingList // 组别属性
      this.form.goodsSkuList = data.goodsSkuList // 库存属性
      this.form.matchChannelsList = data.matchChannelsList // 渠道属性
      this.form.goodsMoblieDesc = data.descPhone // 手机描述
      this.form.matchSignFiled.values = data.matchSignupFieldList // 赛事报名选项
      if ((data.timingPublishFlag && data.timingPublishFlag - 0 === 1) || (data.shelveTime || data.offShelveTime)) {
        this.shelfLevel = SHELF_LEVEL.TIME
        this.form.shelveTime = filters.FormatDate(data.shelveTime || data.timingPublishTime, SHELVE_TIME_FORMAT)
        this.form.offShelveTime = filters.FormatDate(data.offShelveTime, SHELVE_TIME_FORMAT)
      }
      let imgList = data.imgList || []
      this.form.imageList = imgList.map(item => { // 图片
        return item.goodsImgUrl
      })
    },
    _initServiceState (cateCode) {
      let serviceState = {
        editorType: this.editorType, // 编辑类型
        isEditor: !!this.editorType, // 是否为编辑状态
        isSaleEdit: !1, // 销售属性是否可编辑  默认可以编辑
        isTrain: TRAIN_REG.test(cateCode),
        isMatch: MATCH_REG.test(cateCode),
        isTicket: TICKET_REG.test(cateCode),
        isMatchGroup: MATCH_GROUP_CODE.includes(cateCode),
        goodsNameEditState: !1, // 商品名称编辑状态 默认可以编辑
        trainEditState: !1, // 培训仓库中编辑限定不可编辑内容 基本属性中的课程性质  报名填写项
        isHasLimitBuy: true // 是否含限购
      }
      return serviceState
    },
    handleCateChange (val) {
      // 初始化数据
      // 初始化vuex状态
      this.brandList = []
      this.groupItems = []
      this.form.basicProps = []
      this.form.saleProps = []
      this.form.otherProps = []
      this.form.trainSignFiled = {} // 培训
      this.$curGroupIndex = 0
      // 初始化保存草稿数据
      this.form.bizId = undefined
      this.form.goodsCode = undefined
      // this.form.tableData = []
      // 选择服务类目后
      let cateCode = val[val.length - 1] // 区最后一级
      // 获取品牌
      serviceApi.goodsBrand({cateCode}).then(({ data, result, msg }) => {
        this.brandList = data
      })
      // 获取模板
      serviceApi.goodsTemplate({
        // type: 1, // 基本属性-1 销售属性-2 其他属性-3 不传则返回全部
        goodsCateCode: cateCode
      }).then(({ data, result, msg }) => {
        let serviceState = this._initServiceState(cateCode)
        /**
         * 销售属性编辑 isSaleEdit 默认可以编辑 false
         * 编辑类型为草稿、审核不通过  可以编辑
         * 赛事的跑步、其他可以编辑
         * 1、赛事 不是草稿或者可编辑列表  都不能修改
         * 2、培训 仓库中 不能修改  其他都可以修改
         * 3、票务/普通商品 各状态下都可以修改 使用默认
         */
        // 赛事 不是草稿或者可编辑列表  都不能修改
        if (serviceState.isMatch && serviceState.isEditor && serviceState.editorType !== EDIT_TYPE_ENUMS.DRAFTS && !MATCH_ABLE_EDIT_SALES.includes(cateCode)) {
          serviceState.isSaleEdit = !0
        }
        // 培训 仓库中 不能修改  其他都可以修改
        // 培训 仓库中 商品名称不能修改 其他都可以
        if (serviceState.isTrain && serviceState.isEditor && serviceState.editorType === EDIT_TYPE_ENUMS.EDIT) {
          serviceState.isSaleEdit = !0
          serviceState.goodsNameEditState = !0
          serviceState.trainEditState = !0
        }
        // 票务品牌隐藏 票务类目未展开 需要在此处理
        if (serviceState.isTicket) {
          this.stateConfig.brandState = false
        }
        /**
         * 表格限购列处理
         * 赛事去除限购
         * 培训去除限购 v2.5.1
         */
        if (serviceState.isMatch || serviceState.isTrain) {
          serviceState.isHasLimitBuy = false
        }
        this.$store.commit('SERVICE_RELEASE_INIT_STATE', serviceState)
        /**
         * 编辑状态下 赛事团体 抽离比赛方式 matchMode 和 比赛场序matchOrder
         * 保存的时候 将这两项存入基本属性，现需要抽离出来
         */
        if (serviceState.isMatchGroup && serviceState.isEditor) {
          let goodsBaseInfoArr = this.editorData.goodsBaseInfo
          // 团体基本属性 抽出比赛方式 matchMode 和 比赛场序matchOrder
          let matchMode
          let matchOrder
          let newgoodsBaseInfoArr = []
          goodsBaseInfoArr.forEach(item => {
            if (item.name === 'matchMode') {
              matchMode = item
            } else if (item.name === 'matchOrder') {
              matchOrder = item
            } else {
              newgoodsBaseInfoArr.push(item)
            }
          })
          // 加工后的基本属性
          this.editorData.goodsBaseInfo = newgoodsBaseInfoArr
          setTimeout(() => {
            this.form.matchMode = {
              value: matchMode.values[0] + '',
              label: matchMode.valueTexts[0]
            }
            this.form.matchOrder = matchOrder.values
          }, 500)
        }
        data.forEach(item => {
          // 数据排序 及 处理
          let fieldList = item.fieldList && item.fieldList.length ? item.fieldList.sort((a, b) => a.sortValue - b.sortValue) : []
          if (item.type === PROPS_TYPE_ENUMS.BASIC) { // 基本属性
            // 添加value valueText字段  保存对象 方便查找
            this.form.basicProps = this.getProps(fieldList, this.editorData ? this.editorData.goodsBaseInfo : [])
            // this.form.basicProps = this.form.basicProps.filter(item => item.children)
          } else if (item.type === PROPS_TYPE_ENUMS.SALE) { // 销售属性
            this._combineSaleProps(fieldList)
          } else if (item.type === PROPS_TYPE_ENUMS.OTHER) { // 其他属性
            let otherProps = this.getProps(fieldList, this.editorData ? this.editorData.goodsExtInfo : [])
            if (this.editorType) {
              if (this.serviceType.isTrain) {
                // 报名选项
                let trainCourseSignupFieldList = this.editorData.trainCourseSignupFieldList
                let trainSignFileds = trainCourseSignupFieldList.map(item => {
                  let {fieldName, fieldText, isNeed} = item
                  return {fieldName, fieldText, isNeed}
                })
                this.form.trainSignFiled = {
                  values: trainSignFileds
                }
              }
            }
            // 延时处理
            setTimeout(() => {
              this.form.otherProps = otherProps
            }, 1000)
          }
        })
      })
    },
    getProps (propArr, valueArr = []) {
      // debugger
      let newArr = [] // 存储要显示控件的数组
      let parentIndexObj = {} // 存储显示控件attrCode的索引
      let childsObj = {} // 存储级联的对象
      let parentObj = {}
      propArr.forEach(item => {
        let assignItem = {
          value: '',
          valueText: ''
        }
        if (this.editorType) { // 编辑状态
          // 级联状态下可能最后一级没有数据 则不提交而产生找不到 默认为初始值
          let editorItem = valueArr.find(k => k.name === item.attrCode) || {}
          assignItem.editorValues = editorItem.values || []
          assignItem.editorTexts = editorItem.valueTexts || []
        }
        Object.assign(item, assignItem)
        let isParent = item.parentAttrCode === '0' // 是否是父级 父级都直接显示
        if (isParent) {
          newArr.push(item)
          parentIndexObj[item.attrCode] = newArr.length - 1
        } else {
          childsObj[item.attrCode] = item
        }
        parentObj[item.attrCode] = item
      })
      // 对象处理
      Object.keys(childsObj).forEach(okey => {
        let oItem = childsObj[okey]
        let pkey = oItem.parentAttrCode
        if (childsObj.hasOwnProperty(pkey)) {
          childsObj[pkey].children = oItem
          delete childsObj[okey]
        }
      })
      Object.keys(childsObj).forEach(key => {
        let childItem = childsObj[key]
        let pkey = childsObj[key].parentAttrCode
        if (parentIndexObj.hasOwnProperty(pkey)) {
          // 如果父级中能找到 直接插入 此时 为二级
          newArr[parentIndexObj[pkey]].children = childItem
        }
        delete childsObj[key]
      })
      return newArr
    },
    handleSalePropsChange ({isFirst, type, item = [], index, items}) {
      // isFirst是否初始化
      // type 修改类型 plus reduce
      // item 修改的数据
      // items 修改后的数据
      // index 多个组别时需要  预留
      // console.log(type, item, items)
      // debugger
      // console.log('groupssss')
      let isLast = false
      if (type === 'destroy') {
        this.groupItems.splice(index, 1)
        items = this.groupItems[this.groupItems.length - 1]
      } else {
        this.$curGroupIndex ++
        this.groupItems[index] = items
        isLast = Boolean(this.form.saleProps.length === this.$curGroupIndex)
      }
      let newTableArr = []
      // debugger
      items.forEach(it => {
        if (typeof it === 'string') {
          it = {
            name: it
          }
        }
        // 根据索引index去添加或者改变
        let resultGroupArr = []
        let resultItemArr = []
        this.groupItems.forEach((gk, gkIndex) => {
          if (gkIndex === 0) {
            gk.forEach(gkk => {
              resultGroupArr.push([gkk.name])
              resultItemArr.push([gkk])
            })
          } else {
            // debugger
            let tempArr = []
            let tempItemArr = []
            resultGroupArr.forEach((rk, rkIndex) => {
              gk.forEach(gkk => {
                tempArr.push([...rk, gkk.name])
                let curItem = resultItemArr[rkIndex] // 名称和对象索引一致
                tempItemArr.push([...curItem, gkk])
              })
            })
            resultGroupArr = tempArr
            resultItemArr = tempItemArr
          }
        })
        newTableArr = [] // 每次重置
        resultGroupArr.find((rk, rkIndex) => {
          let tableItem = this.form.tableData.find(k => k.group.join(',') === rk.join(','))
          if (tableItem) {
            newTableArr.push(tableItem)
          } else {
            // it.custom = it.code ? 0 : 1 // 没有code则为自定义项，custom = 1
            let curItem = resultItemArr[rkIndex]
            let addItem = Object.assign({}, BASE_TABLE_ROW_DATA, {
              group: rk,
              item: curItem,
              price: isFirst ? curItem[0].price : BASE_TABLE_ROW_DATA.price,
              num: isFirst ? curItem[0].num : BASE_TABLE_ROW_DATA.num,
              linmitNum: isFirst ? curItem[0].linmitNum : BASE_TABLE_ROW_DATA.linmitNum
            })
            newTableArr.push(addItem)
          }
        })
      })
      // 原来实在数组里面赋值，因为items可能为空，需要抽离出来
      this.form.tableData = newTableArr
      if (isFirst && this.editorType && isLast) {
        // 多组别时 处理库存数据
        this.form.tableData = this.form.tableData.map(tk => {
          let valueStr = tk.item.reduce((k1, k2) => (k1.skuCode || k1) + k2.skuCode)
          valueStr = typeof valueStr === 'string' ? valueStr : valueStr.skuCode // 单组别时 会返回tk.item第一个元素
          let skuItem = this.form.goodsSkuList.find(gk => {
            let name = gk.attrCodeList.join('')
            return name === valueStr
          })
          if (skuItem) {
            tk.price = skuItem.price
            tk.num = skuItem.stock
            tk.linmitNum = skuItem.buyTimesLimit
          } else {
            tk.price = BASE_TABLE_ROW_DATA.price
            tk.num = BASE_TABLE_ROW_DATA.num
            tk.linmitNum = BASE_TABLE_ROW_DATA.linmitNum
          }
          return tk
        })
      }
      if (isFirst) {
        this.$timer && clearTimeout(this.$timer)
        this.$timer = setTimeout(_ => {
          this.handleTableDataChange(this.form.tableData)
        })
      } else {
        this.handleTableDataChange(this.form.tableData)
      }
    },
    handleTableDataChange (newTableData) {
      if (this.serviceType.isMatch) {
        // debugger
        let channelList = this.form.channelList.map((item, index) => {
          item.editorArr = item.editorArr || []
          item.channelsGroup = item.channelsGroup || []
          let channelsGroup = []
          // item.channelsGroup = []
          newTableData.forEach((item1, index) => {
            let newData = {}
            item1 = cloneObj(item1)
            let exitChannel = item.channelsGroup.find(k => k.item[0].name === item1.item[0].name) || {}
            // if (item.channelsGroup.length - 1 >= index) {
            // } else {
            //   newData = item1
            // }
            let lotteryNumbers = exitChannel.lotteryNumbers || 0
            newData = Object.assign(exitChannel, item1)
            newData.lotteryNumbers = lotteryNumbers
            // 编辑
            let editItem = item.editorArr.find(k => k.groupDes === item1.item[0].name)
            if (editItem) {
              newData.lotteryNumbers = (editItem.lotteryNumbers - 0) || newData.lotteryNumbers
            }
            channelsGroup[index] = newData
          })
          item.channelsGroup = channelsGroup
          return item
        })
        this.form.channelList = channelList
      }
      if (this.serviceType.isTicket) {
        let newBuyTimes = []
        if (newTableData.length) {
          let exitBuyTimes = this.form.buyTimes
          let firstGroupArr = this.groupItems[0] // 第一组的数据
          newBuyTimes = firstGroupArr.map(item => {
            let exitItem = exitBuyTimes.find(k => k.name === item.name) || {}
            let result = {
              name: item.name,
              label: `场次时间：${item.name}`,
              times: exitItem.times || [],
              startBuyTime: exitItem.startBuyTime || '',
              endBuyTime: exitItem.endBuyTime || ''
            }
            // 编辑状态回复默认值
            if (this.editorType && item.startBuyTime && item.endBuyTime) {
              result.startBuyTime = item.startBuyTime
              result.endBuyTime = item.endBuyTime
              result.times = [filters.FormatDate(item.startBuyTime, SHELVE_TIME_FORMAT), filters.FormatDate(item.endBuyTime, SHELVE_TIME_FORMAT)]
            }
            return result
          })
        } else {
          newBuyTimes = []
        }
        this.form.buyTimes = newBuyTimes
      }
    },
    handelAddChannel () {
      if (this.form.channelList.length >= 6) {
        return
      }
      this.form.channelList.push({
        key: this.unique(),
        channelName: '',
        channelsGroup: cloneObj(this.form.tableData)
      })
    },
    handelDelChannel (index) {
      if (index === 0) {
        this.$message({
          message: '官方渠道，不能删除',
          type: 'warning'
        })
        return !1
      }
      this.form.channelList.splice(index, 1)
    },
    handleAddBrand (brandItem) {
      // 没有品牌时处理
      if (this.brandList) {
        this.brandList.push(brandItem)
      } else {
        this.brandList = [brandItem]
      }
    },
    handleShelfChange (newVal) { // 上架类型变动
      if (newVal === SHELF_LEVEL.TIME) {
        this.shelveTimeRules[0].required = !0
        this.shelveTimeRules[0].message = '请选择定时上架时间'
        this.form.shelveTime = ''
      } else {
        // 默认赋值 防止表单验证不通过
        this.form.shelveTime = filters.FormatDate(new Date(), SHELVE_TIME_FORMAT)
      }
    },
    handleDraft () { // 保存草稿箱
      // console.log('保存草稿箱')
      this.validate(() => {
        this.draftLoading = !0
        let subData = this.getSubData()
        serviceApi.draft(JSON.stringify(subData), {
          context: this,
          successMsg: '草稿保存成功'
        }).then(({ data }) => {
          this.draftLoading = !1
          // 保存 草稿不刷新页面  直接存编辑数据  这些数据 需要在切换类目清除
          this.form.bizId = data.bizId
          this.form.goodsCode = data.goodsCode
          this.previewState = true // 不可点击
          // 跳转草稿箱 暂时不跳转
          // this.$router.push('/drafts')
        }).catch(() => {
          // 保存失败
          this.draftLoading = !1
        })
      })
    },
    handlePreview (type) {
      let goodsCode = this.form.goodsCode
      if (type === 'pc') {
        window.open(`/service/detail/${goodsCode}`)
      }
      if (type === 'app') {
        // v2.4.0 修改
        // 测试：http://m.htxk.com/goods/detail/:goodsCode
        // 开发：http://m.htxk.dev/goods/detail/:goodsCode
        // 预发布：http://yum.hhlyty.cn/goods/detail/:goodsCode
        let { protocol, host } = location
        if (host.indexOf('localhost') !== -1) {
          host = 'm.htxk.kf'
        } else if (host.indexOf('org.htxksport') !== -1) { // 匹配 开发 和 测试环境域名
          protocol = 'https:' // 测试 开发都属于内网其配置的https没有认证，微信认可不能访问
          host = host.replace('org', 'm')
        } else if (host.indexOf('yuorg.hhlyty.cn') !== -1) {
          host = host.replace('yuorg', 'yum')
        } else { // 正式服
          host = 'm.oooseed.com'
        }
        this.qrCodeText = `${protocol}//${host}/goods/detail/${goodsCode}`
        console.log(this.qrCodeText)
        this.qrCodeState = true
      }
    },
    submit () { // 提交后台数据
      /*
      *第二个是前面定义的options参数,options是一个对象，有context,successMsg,errorMsg
      *context:可以为vue对象或者元素对象(button)
      *successMsg:表单提交成功的提示语,默认提示语与context相关，当context为vue对象则提示"提交成功",元素对象则提示"操作成功"，不需要提交语则successMsg = 'none'
      *errorMsg:表单提交失败的提示语,默认提示语与context相关，当context为vue对象则提示"提交失败",元素对象则提示"操作失败"，不需要提交语则errorMsg = 'none'
      */
      this.saveLoading = !0
      let subData = this.getSubData()
      serviceApi.release(JSON.stringify(subData), {context: this}).then(() => {
        // this.saveLoading = !1
        // 跳转
        let nextTouter = '/service/list/check' // 默认跳审核中
        if (this.serviceType.isTicket) { // 立即发布，是跳到到进行中，定时的跳到仓库中
          nextTouter = subData.shelveTime ? '/service/list/store' : '/service/list/underway'
        }
        this.$router.push(nextTouter)
      }).catch(() => {
        this.saveLoading = !1
      })
    },
    getSubData () {
      let subData = {}
      let formData = this.form
      // 更新必须
      if (this.editorType !== EDIT_TYPE_ENUMS.REPUBLISH) { // 非重新发布的编辑都需要
        subData.bizId = formData.bizId
        subData.goodsCode = formData.goodsCode
      }
      // 固定属性
      subData.cateCode = formData.serviceCate[formData.serviceCate.length - 1]
      subData.goodsName = formData.goodsName
      subData.sellPoint = formData.sellPoint
      subData.brand = formData.brand // 品牌
      subData.imageList = formData.imageList
      subData.goodsDesc = formData.goodsDesc
      subData.goodsMoblieDesc = formData.goodsDesc
      // subData.goodsMoblieDesc = formData.goodsMoblieDesc
      // 基本属性
      subData.baseFieldList = []
      formData.basicProps.map(item => {
        let {value, valueText, attrCode, attrName, showModel, sortValue} = item
        let resultItem = {
          sort: sortValue, // 排序
          name: attrCode,
          nameText: attrName,
          valueType: showModel,
          custom: 0 // 销售属性自定义项传1  其他传0
        }
        showModel = item.children ? FORM_TYPE_ENUMS.CASCADER : showModel
        if (showModel === FORM_TYPE_ENUMS.CASCADER) { // 级联
          let vItemTemp = ''
          value = value || []
          value.forEach((vItem, vIndex) => {
            resultItem = cloneObj(resultItem)
            if (vIndex === 0) {
              // 第一级的数据 默认取item
              resultItem.values = [vItem + '']
              resultItem.valueTexts = [valueText[vIndex]]
              vItemTemp = item.children
            } else if (vItemTemp) {
              resultItem.name = vItemTemp.attrCode
              resultItem.nameText = vItemTemp.attrName
              resultItem.valueType = vItemTemp.showModel
              // 针对级联 末级多选做了优化
              resultItem.values = vItem instanceof Array ? vItem : [vItem + '']
              resultItem.valueTexts = vItem instanceof Array ? valueText[vIndex] : [valueText[vIndex]]
              vItemTemp = vItemTemp.children
            }
            subData.baseFieldList.push(resultItem)
          })
        } else {
          value = value || [] // 防止数据渲染出问题
          resultItem.values = value
          resultItem.valueTexts = valueText || value
          subData.baseFieldList.push(resultItem)
        }
      })
      // 赛事团体 比赛方式 比赛场序 加入基本属性
      if (this.serviceType.isMatchGroup) {
        subData.baseFieldList.push({
          // sort: subData.baseFieldList.length,
          name: 'matchMode',
          nameText: '比赛方式',
          values: [formData.matchMode.value],
          valueTexts: [formData.matchMode.label],
          valueType: FORM_TYPE_ENUMS.SELECT,
          custom: 0 // 销售属性自定义项传1  其他传0
        })
        let orderValues = []
        let orderValueTexts = []
        formData.matchOrder.forEach(item => {
          orderValues.push(item.value)
          orderValueTexts.push(item.label)
        })
        subData.baseFieldList.push({
          // sort: subData.baseFieldList.length,
          name: 'matchOrder',
          nameText: '比赛场序',
          values: orderValues,
          valueTexts: [orderValueTexts.join('—')], // 只做详情展示
          valueType: FORM_TYPE_ENUMS.CHECKBOX,
          custom: 0 // 销售属性自定义项传1  其他传0
        })
      }
      // 销售属性
      subData.saleFieldList = formData.tableData.map(tableItem => {
        let fieldList = []
        let {
          group,
          item,
          num = 0,
          linmitNum = 0, // 限制购买次数
          price = 0,
          salePrice = 0
        } = tableItem
        // 需要确定 fieldList 各属性值传递什么
        fieldList = group.map((groupIt, index) => {
          let saleItem = formData.saleProps[index]
          let it = item[index]
          // debugger
          return {
            name: saleItem.attrCode,
            nameText: saleItem.attrName,
            values: [it.value || ''],
            valueTexts: [groupIt], // 肯定有值
            custom: it.custom // 销售属性自定义项传1  其他传0
          }
        })
        let result = {
          fieldList,
          buyLimit: linmitNum,
          number: num,
          price: price,
          marketPrice: salePrice
        }
        // 票务需要增加起止时间
        if (this.serviceType.isTicket) {
          // 根据第一组的名称 获取起止时间
          let buyTimeItem = formData.buyTimes.find(k => k.name === group[0]) || {}
          let {startBuyTime, endBuyTime} = buyTimeItem
          result.startBuyTime = startBuyTime
          result.endBuyTime = endBuyTime
        }
        return result
      })
      // 其他属性
      subData.otherFieldList = []
      formData.otherProps.forEach(item => {
        let {value, valueText, attrCode, attrName, showModel, sortValue} = item
        let resultItem = {
          sort: sortValue, // 排序
          name: attrCode,
          nameText: attrName,
          valueType: showModel,
          custom: 0 // 销售属性自定义项传1  其他传0
        }
        showModel = item.children ? FORM_TYPE_ENUMS.CASCADER : showModel
        if (showModel === FORM_TYPE_ENUMS.CASCADER) { // 级联
          let vItemTemp = ''
          value.forEach((vItem, vIndex) => {
            resultItem = cloneObj(resultItem)
            if (vIndex === 0) {
              // 第一级的数据 默认取item
              resultItem.values = [vItem]
              resultItem.valueTexts = [valueText[vIndex]]
              vItemTemp = item.children
            } else if (vItemTemp) {
              resultItem.name = vItemTemp.attrCode
              resultItem.nameText = vItemTemp.attrName
              resultItem.valueType = vItemTemp.showModel
              resultItem.values = [vItem]
              resultItem.valueTexts = [valueText[vIndex]]
              vItemTemp = vItemTemp.children
            }
            // 插入
            subData.otherFieldList.push(resultItem)
          })
        } else {
          resultItem.values = value
          resultItem.valueTexts = valueText
          // 插入
          subData.otherFieldList.push(resultItem)
        }
      })
      // 渠道
      if (this.serviceType.isMatch) {
        let channelItem = this.form.channelList.map(item => {
          let channelName = item.channelName
          let channelsGroup = item.channelsGroup.map(cgItem => {
            let resultItem = {}
            resultItem.groupType = cgItem.item[0].value
            resultItem.groupDes = cgItem.item[0].name // 赛事组别类型描述
            resultItem.lotteryNumbers = cgItem.lotteryNumbers // 名额
            return resultItem
          })
          return {
            channelName,
            channelsGroup
          }
        })
        subData.extendFieldLsit = [
          {
            name: 'matchChannelsList',
            valueType: 5,
            values: [JSON.stringify(channelItem)],
            valueTexts: [JSON.stringify(channelItem)]
          },
          formData.matchSignFiled.result
        ]
        // 赛事团体 比赛方式 比赛场序 加入基本属性
        // if (this.serviceType.isMatchGroup) {
        //   subData.extendFieldLsit.push({
        //     // sort: subData.baseFieldList.length,
        //     name: 'matchMode',
        //     nameText: '比赛方式',
        //     values: [formData.matchMode.value],
        //     valueTexts: [formData.matchMode.label],
        //     valueType: FORM_TYPE_ENUMS.SELECT,
        //     custom: 0 // 销售属性自定义项传1  其他传0
        //   })
        //   let aenum = { '男单': 1, '男双': '11', '女单': '2', '女双': '22', '混双': '12' }
        //   let orderValues = formData.matchOrder.map(k => aenum[k])
        //   subData.extendFieldLsit.push({
        //     // sort: subData.baseFieldList.length,
        //     name: 'matchOrder',
        //     nameText: '比赛场序',
        //     values: orderValues,
        //     valueTexts: formData.matchOrder,
        //     valueType: FORM_TYPE_ENUMS.CHECKBOX,
        //     custom: 0 // 销售属性自定义项传1  其他传0
        //   })
        // }
      }
      // 票务 上架方式 是否需要审核
      if (this.serviceType.isTicket) {
        // 如果不为定时上架 则不传
        subData.shelveTime = this.shelfLevel === SHELF_LEVEL.TIME ? Date.parse(formData.shelveTime) : undefined
      }
      // 培训处理
      if (this.serviceType.isTrain) {
        subData.extendFieldLsit = [formData.trainSignFiled]
        // 培训上架方式处理
        if (this.shelfLevel === SHELF_LEVEL.TIME) {
          subData.shelveTime = Date.parse(formData.shelveTime)
          subData.offShelveTime = Date.parse(formData.offShelveTime)
        } else {
          subData.shelveTime = undefined
          subData.offShelveTime = undefined
        }
      }
      // subData.extendFieldLsit = formData.extendFieldLsit.map(item => {
      //   // 拓展属性
      // })
      return subData
    },
    _getCateListByCateCode (cateCode) {
      // 通过类目code 从平级目录中获取全路径code
      let cateCodeArr = []
      let cateItem = this._categoryList.find(item => item.cateCode === cateCode)
      if (cateItem) {
        cateCodeArr = [cateCode]
        let pArr = this._getCateListByCateCode(cateItem.parentCateCode)
        cateCodeArr = pArr.concat(cateCodeArr)
      }
      return cateCodeArr
    },
    _recursionArr (reArr) { // 平级类目转换层树状类目
      let newArr = []
      let childObj = {}
      // let i = 0
      reArr.forEach((item, index) => {
        if (item.parentCateCode - 0 === 0) {
          newArr.push(item)
          // arr.splice(index, 1)
        } else {
          if (childObj.hasOwnProperty(item.parentCateCode)) {
            childObj[item.parentCateCode].push(item)
          } else {
            childObj[item.parentCateCode] = [item]
          }
        }
        // console.log('循环次数===' + i++)
      })
      function recursion (itemArr, obj) {
        itemArr = itemArr.map(item2 => {
          // console.log('循环次数===' + i++)
          if (obj.hasOwnProperty(item2.cateCode)) {
            item2.children = obj[item2.cateCode]
          }
          if (item2.children) {
            item2.children = recursion(item2.children, obj)
          }
          return item2
        })
        // console.log(flag)
        return itemArr
      }
      return recursion(newArr, childObj)
    },
    handleTrainPropChange (newVl, oldVl) {
      // 培训课程性质改变处理
      let ckIndex = -1
      if (newVl === '次课') {
        this.$trainTimer = setTimeout(_ => {
          ckIndex = this.form.saleProps.findIndex(k => k.attrCode === TRAIN_SALE_ITEM.attrCode)
          if (this.form.saleProps.length) {
            ckIndex === -1 && this.form.saleProps.push(cloneObj(TRAIN_SALE_ITEM))
            clearTimeout(this.$trainTimer)
          } else {
            this.handleTrainPropChange(newVl, oldVl)
          }
        })
      } else {
        ckIndex = this.form.saleProps.findIndex(k => k.attrCode === TRAIN_SALE_ITEM.attrCode)
        ckIndex !== -1 && this.form.saleProps.splice(ckIndex, 1)
        this.$trainTimer && clearTimeout(this.$trainTimer)
      }
    },
    _combineSaleProps (fieldList) {
      if (this.editorType) {
        let ckIndex = this.form.attributeMappingList.findIndex(k => k.attrCode === TRAIN_SALE_ITEM.attrCode)
        if (ckIndex !== -1) {
          fieldList.push(cloneObj(TRAIN_SALE_ITEM))
        }
      }
      let saleProps = fieldList.map((item, itemIndex) => {
        let values = []
        if (this.editorType) {
          values = this.form.attributeMappingList.filter(k => k.parentAttrCode === item.attrCode)
          values = values.map((vk, index) => {
            // 根据code对应库存
            // let skuItem = this.form.goodsSkuList.find(gk => gk.attrCodeList[0] === vk.attrCode) || {}
            // let skuItem = this.form.goodsSkuList.find(gk => gk.skuItemList[0].attrCode === vk.attrCode) || {}
            let skuItem = this.form.goodsSkuList.find(gk => gk.skuItemList.find(sk => sk.attrCode === vk.attrCode)) || {}
            vk.price = skuItem.price
            vk.num = skuItem.stock
            vk.linmitNum = skuItem.buyTimesLimit
            // 票务数据
            if (this.serviceType.isTicket) {
              vk.startBuyTime = skuItem.startBuyTime
              vk.endBuyTime = skuItem.endBuyTime
            }
            return vk
          })
          // 跑步特殊处理
          /**
           * change detail
           * 开放赛事渠道功能，导致已有数据没有渠道，编辑是渠道列表为空
           * 现处理 但返回数据为空数组时，不修改默认渠道 留给用户修改
           */
          if (this.serviceType.isMatch && this.form.matchChannelsList.length) {
            this.form.channelList = this.form.matchChannelsList.map(k => {
              let channelItem = {}
              channelItem.channelName = k.channelName
              channelItem.channelsGroup = []
              channelItem.editorArr = k.channelsGroup
              // channelItem.channelsGroup = k.channelsGroup.map(kk => {
              //   let groupItem = {}
              //   groupItem.group = [kk.groupDes]
              //   groupItem.lotteryNumbers = kk.lotteryNumbers
              //   groupItem = Object.assign(BASE_TABLE_ROW_DATA, groupItem)
              //   return groupItem
              // })
              return channelItem
            })
          }
        }
        item.editorValues = values
        item.data = []
        return item
      })
      // 延时处理
      setTimeout(() => {
        this.form.saleProps = saleProps
      }, 500)
    }
  }
}
</script>
<style lang="scss">
 
  .release-wrapper{
    .group-table{
      .el-table__empty-block{
        border-bottom: 1px solid #f0f0f0;
        border-right: 1px solid #f0f0f0;
      }
    }
    .goodsName{
      .el-input.is-disabled{
        .el-input__inner{
          opacity: 1;
          border: 1px solid #f0f0f0;
          color: $color-sub;
          background: #fafafa;
        }
      }
    }
    .qrcode-dialog{
      width: 400px;
      height: 442px;
      border-radius: 6px;
      margin: 0 84px;
      text-align: center;
      .el-dialog__body{
        .title{
          margin-bottom: 30px;
        }
        .qr-code-img{
          margin: 0 54px;
        }
      }
    }
  }
</style>
<style lang="scss" scoped>
 
  .release-wrapper{
    .sale-props-item{
      .group-title{
        display: block;
        text-align:left;
      }
    }
    .logo-upload {
      width: 160px;
      height: 90px;
    }

    .run-type {
      width: 50px;
      text-align: right;
      display: inline-block;
    }

    .mb10 {
      margin-bottom: 10px;
    }

    .disabled {
      cursor: not-allowed
    }
    .tips.tips-left{
      text-align: right;
      font-size: 12px;
      color: $color-sub;
      .num{
        color: #333;
        padding: 0 2px;
        font-weight: 700;
      }
    }
    .warn-tips{
      &.mt10{
        margin-top: 10px;
      }
    }
    .form-help{
      &.mt10{
        margin-top: 10px;
      }
      &.save-help{
        text-align: center;
      }
    }
  }
</style>
<style lang="scss">
  .release-wrapper{
    .channel_group_wrapper{
      & > .el-form-item > .el-form-item__content{
        margin-left: 0 !important;
        .group-item{
          .group-content{
            padding: 15px 15px 25px 0;
            .el-form-item__error{
              padding-top: 8px;
            }
          }
        }
      }
    }
    // .release_channel_group{
    //   margin: 0 !important;
    //   .group-item{
    //     position: relative;
    //     padding: 0 !important;
    //     .channel_label{
    //       position: absolute;
    //       width: 142px;
    //       left: -142px;
    //     }
    //   }
    // }
  }
</style>
